<template>
  <div>
    <!-- 顶部的面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/content/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider content-position="left"></el-divider>

    <!-- 操作区域 -->
    <div style="margin: 0 0 20px 0;">
      <el-button type="primary" size="small" @click="$router.push('/admin/content/goods/add-new')">发布商品</el-button>
    </div>

    <!-- 表格 -->
    <el-divider content-position="left">商品列表</el-divider>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" align="center" width="50"></el-table-column>
      <el-table-column label="类别" align="center" width="80">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.categoryName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名称" header-align="center"
                       show-overflow-tooltip widh="60"></el-table-column>
      <el-table-column prop="goodsPrice" label="售价" width="80" align="center"></el-table-column>
      <el-table-column prop="goodsInfo" label="商品信息" width="220" header-align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column prop="goodsNumber" label="商品库存" width="50" align="center"></el-table-column>
      <el-table-column label="上架状态" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleStatus(scope.row)"
              v-model="scope.row.goodsStatus"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="详情" width="80" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="showGoodsDetail(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle size="mini"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle size="mini"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="margin: 10px 0; text-align: right;">
      <el-pagination
          @current-change="changePage"
          layout="total, prev, pager, next"
          :hide-on-single-page="true"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="total">
      </el-pagination>
    </div>

    <!-- 预览商品详情的弹出框 -->
    <el-dialog class="goods-preview-dialog" title="查看商品详情" :visible.sync="goodsPreviewDialogVisible">
      <el-descriptions :column="1" border label-class-name="description-label">
        <el-descriptions-item label="ID">{{ goodsPreviewData.id }}</el-descriptions-item>
        <el-descriptions-item label="类别">{{ goodsPreviewData.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ goodsPreviewData.goodsName }}</el-descriptions-item>
        <el-descriptions-item label="商品信息">{{ goodsPreviewData.goodsInfo }}</el-descriptions-item>
        <el-descriptions-item label="商品价格">{{ goodsPreviewData.goodsPrice }}</el-descriptions-item>
        <el-descriptions-item label="商品图像">{{ goodsPreviewData.goodsLogo }}</el-descriptions-item>
        <el-descriptions-item label="商品库存">{{ goodsPreviewData.goodsNumber }}</el-descriptions-item>
        <el-descriptions-item label="上架状态">
          <el-tag type="success" v-if="goodsPreviewData.goodsStatus == 1">上架</el-tag>
          <el-tag type="info" v-else-if="goodsPreviewData.goodsStatus == 0">下架</el-tag>
          <el-tag type="danger" v-else>拒绝审核</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ goodsPreviewData.gmtCreate }}</el-descriptions-item>
        <el-descriptions-item label="最后修改时间">{{ goodsPreviewData.gmtModified }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 修改数据的表单 -->
    <el-dialog title="编辑商品数据" :visible.sync="editFormVisible">
      <el-form :model="editForm" :rules="editRules" label-width="120px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="editForm.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="editForm.goodsPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品信息" prop="goodsInfo">
          <el-input v-model="editForm.goodsInfo"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="goodsLogo">
          <el-input v-model="editForm.goodsLogo"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="goodsNumber">
          <el-input v-model="editForm.goodsNumber"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 分页相关数据
      currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
      pageSize: 20,
      total: 0,
      // 预览商品详情相关数据
      goodsPreviewDialogVisible: false,
      goodsPreviewData: {},
      // 编辑对话框相关数据
      editFormVisible: false,
      editForm: {
        id:'',
        goodsName: '',
        goodsPrice: '',
        goodsInfo: '',
        goodsLogo: '',
        goodsNumber: '',


      },
      // 编辑表单规则
      editRules: {
        goodsName: [
          {required: true, message: '请输入类别名称', trigger: 'blur'},
          {min: 2, max: 15, message: '类别名称长度必须在 2 到 15 个字符', trigger: 'blur'}
        ],
        goodsLogo: [
          {required: true, message: '请输入图标图片的URL', trigger: 'blur'},
          {min: 20, max: 200, message: '图标图片的URL长度必须在 20 到 200 个字符', trigger: 'blur'}
        ],
      }
    };
  },
  methods: {
    // 切换分页
    changePage(page) {
      this.$router.replace('?page=' + page);
      this.loadGoodsList();
    },
    // 切换审核状态
    toggleStatus(tableItem) {
      let statusText = ['下架', '上架'];
      let url = 'http://localhost:9080/content/goods/' + tableItem.id;
      if (tableItem.goodsStatus == 0) {
        url += '/pull-off';
      } else {
        url += '/put-on';
      }
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: statusText[tableItem.goodsStatus] + '商品成功！',
            type: 'success'
          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              if (jsonResult.state == 40400) {
                this.loadGoodsList();
              }
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 弹出修改对话框
    openEditDialog(tableItem) {
      let url = 'http://localhost:9080/content/goods/' + tableItem.id;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.editForm = jsonResult.data;
          this.editFormVisible = true;
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadGoodsList();
            }
          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 执行修改
    handleEdit() {
      let url = 'http://localhost:9080/content/goods/' + this.editForm.id + '/update';
      console.log('url = ' + url);

      let formData = this.qs.stringify(this.editForm);
      console.log('formData = ' + formData);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
          this.editFormVisible = false;
          this.loadGoodsList();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.editFormVisible = false;
              this.loadGoodsList();
            }
          });
        } else if (jsonResult.state == 40900) {
          this.$message.error(jsonResult.message);
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });


    },
    // 弹出删除确认框
    openDeleteConfirm(tableItem) {
      let message = '此操作将永久删除商品【' + tableItem.goodsName + '】，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(tableItem);
      }).catch(() => {
      });
    },
    // 执行删除
    handleDelete(tableItem) {
      let url = 'http://localhost:9080/content/goods/' + tableItem.id + '/delete';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '删除【' + tableItem.goodsName + '】类别成功！',
            type: 'success'
          });
          this.loadGoodsList();
        } else if (jsonResult.state == 40400) {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadGoodsList();
            }
          });
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 显示商品详情
    showGoodsDetail(goods) {
      let url = 'http://localhost:9080/content/goods/' + goods.id;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.goodsPreviewData = jsonResult.data;
          this.goodsPreviewDialogVisible = true;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
              this.loadGoodsList();
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    },
    // 加载商品列表
    loadGoodsList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let url = 'http://localhost:9080/content/goods?page=' + page;
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.currentPage = jsonResult.data.currentPage;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    }
  },
  mounted() {
    this.loadGoodsList();
  }
}
</script>

<style>
.goods-preview-dialog {
}

.goods-preview-dialog .description-label {
  width: 150px;
}

.goods-preview-dialog .picture-item {
  width: 160px;
  height: 90px;
  margin-right: 16px;
  margin-bottom: 10px;
  border-radius: 3px;
  float: left;
}
</style>